package net.bwie.realtime.jtp.dwd.log.function;

import com.alibaba.fastjson.JSONObject;
import net.bwie.realtime.jtp.utils.DateTimeUtil;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

public class AdjustIsNewProcessFunction extends KeyedProcessFunction<String, String, String> {
    private transient ValueState<String> fistDataState =  null;

    @Override
    public void open(Configuration parameters) throws Exception {
        ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("fist-data", String.class);
        fistDataState = getRuntimeContext().getState(stateDescriptor);
//        fistDataState = getRuntimeContext().getState(new ValueStateDescriptor<String>("fist-data",String.class));
    }

    @Override
    public void processElement(String s,
                               KeyedProcessFunction<String, String, String>.Context context,
                               Collector<String> collector) throws Exception {
        String fistData = fistDataState.value();

        //选择 JSONObject.parseObject() 是业务需求（解析 JSON 提取字段）、技术栈（FastJSON 已集成）、性能（流处理高吞吐）共同作用的结果，
        JSONObject jsonObject = JSONObject.parseObject(s);

        String isNew = jsonObject.getJSONObject("common").getString("is_new");
        Long ts = jsonObject.getLong("ts");

        if("1".equals(isNew)){
            if(fistData == null){
                fistDataState.update(DateTimeUtil.convertLongToString(ts, DateTimeUtil.DATE_TIME_FORMAT));
            }
            else{
                if (!fistData.equals(DateTimeUtil.convertLongToString(ts, DateTimeUtil.DATE_TIME_FORMAT))){
                    jsonObject.getJSONObject("common").put("is_new",0);
                }
            }
        }
        else {
            if (null == fistData){
                fistDataState.update(DateTimeUtil.convertLongToString(ts - 86400000L, DateTimeUtil.DATE_TIME_FORMAT));
            }
        }
        collector.collect(jsonObject.toJSONString());
    }
}